import 'package:dio/dio.dart';

import 'package:sainbainu/common/http/exception.dart';

import 'package:sainbainu/common/services/user.dart';

/// 自定义拦截器
class HttpInterceptor extends Interceptor {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    /// 请求头加入token
    options.headers['Authorization-Social-APP'] =
        'Bearer ${UserService.to.token}';
    super.onRequest(options, handler);
  }

  @override
  Future onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) async {
    Map<String, dynamic> data = response.data;
    if (data['code'] != 200) {
      CustomHttpException httpException = CustomHttpException(
        code: data['code'],
        message: data['msg'],
      );
      DioException dioError = DioException(
        requestOptions: response.requestOptions,
        response: response,
        type: DioExceptionType.badResponse,
        error: httpException,
      );
      return handler.reject(dioError);
    } else {
      return super.onResponse(response, handler);
    }
  }

  @override
  Future onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    /// httpException异常类接管dio的error
    CustomHttpException httpException = CustomHttpException.create(err);
    err = err.copyWith(error: httpException);

    return super.onError(err, handler);
  }
}
